package wxwoa

import (
	"fmt"
	"net/http"
	"strings"

	"gitee.com/chenrh/finego/app"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type WxTemplateDemo struct {
	tempID string
}

// WxTemplateMessageController 模板消息
type WxTemplateMessageController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context
}

// BeforeActivation Mvc 注册路由
func (c *WxTemplateMessageController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "/send_template_message", "PostSendTemplateMessage")
	b.Handle("GET", "/dft_temp_msg", "GetDefaultTemplateMessagePage")
}

// PostSendTemplateMessage 发送模板消息
func (c *WxTemplateMessageController) PostSendTemplateMessage(ctx iris.Context) {
	openid := ctx.FormValue("openid")

	// demo: 您好，你的余额还有{{Amount.DATA}}元。 感谢您的使用！
	demojson := `{
		"touser":"%s",
		"template_id":"Es6uCNPjIw4MduhWU1qpqtlnkcIX2eGTKyW39Yrrw1g",
		"url":"http://weixin.qq.com/download",          
		"data":{
			"Amount": {
				"value":"1059200.78",
				"color":"#006633"
			}
		}
	}
	`
	demojson = fmt.Sprintf(demojson, openid)
	accessToken := WxAccessToken{}.AccessToken(ctx)
	url := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken

	req, err := http.NewRequest("POST", url, strings.NewReader(demojson))
	if err != nil {
		app.LoggerWithCtx(ctx).Error(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": "模板消息发送失败" + err.Error()})
		return
	}

	// 伪装头部
	// req.Header = c.MyHttpHeader("http://www.sse.com.cn/assortment/stock/list/share/")

	//提交请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		app.LoggerWithCtx(ctx).Error(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": "模板消息发送失败" + err.Error()})
		return
	}
	defer resp.Body.Close()

	ctx.JSON(iris.Map{"flag": true, "msg": "发送成功，请打开公众号查看"})
}

// GetDefaultTemplateMessagePage 默认测试界面
func (c *WxTemplateMessageController) GetDefaultTemplateMessagePage(ctx iris.Context) mvc.Result {
	openid := ctx.URLParam("openid")

	return mvc.View{
		Name: "wxapi/wx.template.html",
		Data: iris.Map{
			"Title":  "发送测试的模板消息",
			"OpenID": openid,
		},
	}
}
